package com.hsxc.cdz.controller.wxController;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hsxc.cdz.controller.wxController.service.CoreService;
import com.hsxc.cdz.controller.wxController.thread.TokenThread;
import com.hsxc.cdz.controller.wxController.util.Constants;
import com.hsxc.cdz.controller.wxController.util.SignUtil;
/** 
* @author  wpfei
* @version 创建时间：2016年7月4日 上午13:24:06 
* 类说明 ：
*/
//微信服务号token握手
@Controller
@RequestMapping("/api")
public class HandShaker  {
	protected static Logger log= Logger.getLogger("WXListener");
	@RequestMapping(value="/scan",method = RequestMethod.GET)
	@ResponseBody
        public void handshake(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
        	request.setCharacterEncoding("UTF-8");  
    	    response.setCharacterEncoding("UTF-8");
            String signature = request.getParameter("signature");
            String timestamp = request.getParameter("timestamp");
            String nonce = request.getParameter("nonce");
            String echostr = request.getParameter("echostr");
            PrintWriter out = response.getWriter();
            if (SignUtil.checkSignature(signature, timestamp, nonce)) {
                out.print(echostr);
            }       
            out = null;
       
        }

	@RequestMapping(value="/scan",method = RequestMethod.POST)
	@ResponseBody
	public String getWeiXinMessage(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）  
        request.setCharacterEncoding("UTF-8");  //微信服务器POST消息时用的是UTF-8编码，在接收时也要用同样的编码，否则中文会乱码；
        response.setCharacterEncoding("UTF-8"); //在响应消息（回复消息给用户）时，也将编码方式设置为UTF-8，原理同上；
        //初始化配置文件
       //调用CoreService类的processRequest方法接收、处理消息，并得到处理结果；
        String result = "";  
        /** 判断是否是微信接入激活验证，只有首次接入验证时才会收到echostr参数，此时需要把它直接返回 */  
        String echostr = request.getParameter("echostr");  
        if (echostr != null && echostr.length() > 1) {  
            result = echostr;  
        } else {  
			//正常的微信处理流程  
        	result = CoreService.processRequest(request);  
        }  
        try {  
            OutputStream os = response.getOutputStream();  
            os.write(result.getBytes("UTF-8"));  
            os.flush();  
            os.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }       
       // response.getWriter().write(respMessage);
        return result;
    
	}
	//触发启动线程 
	@RequestMapping(value="/threadsta",method = RequestMethod.GET)
	@ResponseBody
	public Object threadStart(){
		   String tips="fail";
		  System.out.println("开始启动线程");
          if ("".equals(Constants.APP_ID) || "".equals(Constants.APPSECRET)) {
              log.error("appid and appsecret configuration error, please check carefully.");
          } else {
              // 启动定时获取access_token的线程
          	 System.out.println("启动TOKEN线程");
              new Thread(new TokenThread()).start();            
             tips = "success";
      }
		return tips;
	}



}
